# encoding:utf-8
import traceback

import jwt
from flask import current_app, g

from datetime import datetime, timedelta


def generate_jwt(payload, expiry, secret=None):
    """
    生成jwt
    :param payload: dict 荷载信息
    :param expiry: date  有效期
    :param secret: str  盐
    :return:  token
    """
    _payload = {
        'exp': expiry
    }
    token = None
    try:
        _payload.update(payload)
        if not secret:
            secret = current_app.config['JWT_SECRET']
        # 生成token       _payload 荷载信息：用户账号信息、 有效期   secret 盐
        token = jwt.encode(_payload, secret, algorithm='HS256')
    except Exception as e:
        error = traceback.format_exc()
        print('generate_jwt is error:{}'.format(error))
    return token


def verify_jwt(token, secret=None):
    """
    校验token
    :param token: 需要校验的token
    :param secret: 盐
    :return: payload
    """
    payload = None
    if not secret:
        secret = current_app.config['JWT_SECRET']
    try:
        payload = jwt.decode(token, secret, algorithms='HS256')
    except:
        error = traceback.format_exc()
        print('error:', error)
        payload = None
    return payload


def _generate_token(account, user_id, refresh=True):
    """
    生成token
    :param user_id:
    :return:
    """
    pass


def refresh_token():
    """
    刷新token
    :return:
    """
    if g.account is not None and g.is_refresh is True:
        token, _ = _generate_token(g.account, g.user_id, refresh=False)
        return {'message': 'ok', 'data': {'token': token}, 'code': 200}
    else:
        return {'message': 'Invalid refresh token', 'code': 500}


